/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufc.virtual.pregnant.persistencia;

import br.ufc.virtual.pregnant.entidades.Disciplina;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Leonardo Oliveira Moreira
 *
 */
public class DisciplinaDAO extends DAO {

    public DisciplinaDAO() throws SQLException {
        super();
    }

    public Disciplina getDisciplina(String codigo) throws SQLException {
        String sql = "";
        sql += "SELECT codigo, nome, carga_horaria, credito FROM disciplina WHERE codigo = '" + codigo + "'";
        Disciplina item = null;
        try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                item = new Disciplina();
                item.setCodigo(resultSet.getString("codigo"));
                item.setNome(resultSet.getString("nome"));
                item.setCargaHoraria(resultSet.getInt("carga_horaria"));
                item.setCredito(resultSet.getInt("credito"));
            }
            resultSet.close();
            statement.close();
        }
        if (item == null) {
            throw new SQLException("Disciplina não encontrada");
        }
        return item;
    }

    public List<Disciplina> getDisciplinas() throws SQLException {
        String sql = "";
        sql += "SELECT codigo, nome, carga_horaria, credito FROM disciplina";
        List<Disciplina> resultado = new ArrayList<>();
        try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                Disciplina item = new Disciplina();
                item.setCodigo(resultSet.getString("codigo"));
                item.setNome(resultSet.getString("nome"));
                item.setCargaHoraria(resultSet.getInt("carga_horaria"));
                item.setCredito(resultSet.getInt("credito"));
                resultado.add(item);
            }
            resultSet.close();
            statement.close();
        }
        if (resultado.isEmpty()) {
            throw new SQLException("Nenhuma disciplina foi encontrada");
        }
        return resultado;
    }

    public boolean inserirDisciplina(Disciplina item) throws SQLException {
        String sql = "";
        sql += "INSERT INTO disciplina (codigo, nome, carga_horaria, credito)";
        sql += " VALUES ";
        sql += "(";
        sql += "'" + item.getCodigo() + "', ";
        sql += "'" + item.getNome() + "', ";
        sql += "" + item.getCargaHoraria() + ", ";
        sql += "" + item.getCredito() + "";
        sql += ")";
        int result;
        try (Statement statement = connection.createStatement()) {
            result = statement.executeUpdate(sql);
            statement.close();
        }
        if (result != 1) {
            throw new SQLException("Não foi possível inserir esta disciplina");
        }
        return (result == 1);
    }

    public static void main(String[] args) {
        /*
         try {
         List<Disciplina> disciplinas = new ArrayList<Disciplina>();
         File f = new File("C:\\Users\\Leonardo\\Documents\\Disciplinas.txt");
         BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "ISO-8859-1"));
         while (reader.ready()) {
         String registro = reader.readLine();
         System.out.println(registro);
         if (registro.split(";").length != 4) {
         throw new IOException("Erro no Split");
         }
         Disciplina d = new Disciplina();
         d.setCodigo(registro.split(";")[0]);
         d.setNome(registro.split(";")[1]);
         d.setCargaHoraria(Integer.parseInt(registro.split(";")[2]));
         d.setCredito(Integer.parseInt(registro.split(";")[3]));
         if (disciplinas.contains(d)) {
         System.out.println("A disciplina " + d.toString() + " já existe");
         } else {
         disciplinas.add(d);
         }
         }
         reader.close();
         try {
         DisciplinaDAO dao = new DisciplinaDAO();
         System.out.println("Número de Disciplinas: " + disciplinas.size());
         int disciplinasInseridas = 0;
         for (Disciplina d : disciplinas) {
         if (dao.inserirDisciplina(d)) {
         disciplinasInseridas++;
         } else {
         dao.rollback();
         dao.close();
         throw new IOException("Erro ao inserir a disciplina " + d.toString());
         }
         }
         dao.commit();
         dao.close();
         System.out.println("Número de disciplinas inseridas: " + disciplinasInseridas);
         } catch (SQLException ex) {
         System.out.println(ex.getMessage());
         }
         } catch (FileNotFoundException ex) {
         System.out.println(ex.getMessage());
         } catch (IOException ex) {
         System.out.println(ex.getMessage());
         }
         */

        try {
            DisciplinaDAO dao = new DisciplinaDAO();
            List<Disciplina> list = dao.getDisciplinas();
            if (list.size() == 0) {
                System.out.println("Não há disciplinas");
            }
            for (Disciplina d : list) {
                System.out.println(d);
            }
            dao.commit();
            dao.close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
